@echo off

:: BatchGotAdmin
:-------------------------------------
REM  --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"

REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )

:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
    exit /B

:gotAdmin
    if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" )
    pushd "%CD%"
    CD /D "%~dp0"
:--------------------------------------

chcp 65001 >nul
setlocal enabledelayedexpansion

title Symbolic Link Creator - Group Mode

set "ini_file=sc.ini"
set "link_count=0"
set "in_active_block=0"
set "current_target="
set "target_count=0"
set "current_group_targets="

cls
echo ======================================================
echo            Symbolic Link Creator
echo             WWW.CDSJCC.CN
echo      https://gitee.com/cdsjcc/jyys/
echo ======================================================
echo.
echo Reading configuration from %ini_file%...
echo.

for /f "usebackq tokens=* delims=" %%L in ("%ini_file%") do (
    set "line=%%L"
    rem Remove spaces for keyword matching
    set "clean_line=!line: =!"

    if "!clean_line!"=="{kq}:=1" (
        set in_active_block=1
        set current_target=
        set target_count=0
        set current_group_targets=
        echo Found an active group. Reading...
    )
    if "!clean_line!"=="{kq}:=0" ( set in_active_block=0 )
    if "!clean_line!"=="{/kq}" (
        if !in_active_block! equ 1 echo Finished reading active group.
        set in_active_block=0
        set current_target=
        set target_count=0
        set current_group_targets=
    )

    if !in_active_block! equ 1 (
        for /f "tokens=1,* delims==" %%a in ('echo !line!') do (
            set "key=%%a"
            set "value=%%b"
            set "key=!key: =!"

            if /i "!key!"=="[mb]" (
                set /a target_count+=1
                set "group_target_!target_count!=!value!"
                if "!current_group_targets!"=="" (
                    set "current_group_targets=!value!"
                ) else (
                    set "current_group_targets=!current_group_targets!;!value!"
                )
            )
            if /i "!key!"=="[ys]" (
                if !target_count! gtr 0 (
                    for /l %%t in (1, 1, !target_count!) do (
                        set /a link_count+=1
                        set "source_!link_count!=!value!"
                        set "target_!link_count!=!group_target_%%t!"
                    )
                ) else (
                    echo WARNING: Found source [ys] without any target [mb] in an active block. Skipping.
                )
            )
        )
    )
)

echo.
echo The following %link_count% symbolic links will be created from active groups:
echo ======================================================================
if %link_count% equ 0 (
    echo No active source paths found.
) else (
    for /l %%i in (1, 1, !link_count!) do (
        set "source_path=!source_%%i!"
        set "target_path=!target_%%i!"
        echo   %%i. !source_path!
        echo      --^> !target_path!
    )
)
echo ======================================================================
echo.

if %link_count% equ 0 (
    pause
    exit /b
)

:confirmation
set /p "confirm=Do you want to create these symbolic links? (Y/N): "
if /i "%confirm%"=="Y" goto create_links
if /i "%confirm%"=="N" goto exit_script
echo Invalid input. Please enter Y or N.
goto confirmation

:create_links
echo.
echo Collecting unique target directories...
echo.

rem Collect unique target directories
set "unique_target_count=0"
for /l %%i in (1, 1, %link_count%) do (
    set "current_target_path=!target_%%i!"
    set "is_duplicate=0"
    
    rem Check if this target path already exists in unique list
    for /l %%j in (1, 1, !unique_target_count!) do (
        if "!current_target_path!"=="!unique_target_%%j!" (
            set "is_duplicate=1"
        )
    )
    
    rem Add to unique list if not duplicate
    if !is_duplicate! equ 0 (
        set /a unique_target_count+=1
        set "unique_target_!unique_target_count!=!current_target_path!"
    )
)

echo Found !unique_target_count! unique target directories.
echo.

rem Check if any target directories have content
set "has_content=0"
set "total_files=0"
set "total_dirs=0"

echo Scanning target directories for existing content...
echo ======================================================================

for /l %%i in (1, 1, !unique_target_count!) do (
    set "target_dir=!unique_target_%%i!"
    echo Checking: !target_dir!
    
    if exist "!target_dir!\" (
        set "dir_file_count=0"
        set "dir_dir_count=0"
        
        rem Count files in directory
        for /f %%f in ('dir "!target_dir!" /b /a-d 2^>nul ^| find /c /v ""') do set "dir_file_count=%%f"
        
        rem Count subdirectories in directory
        for /f %%d in ('dir "!target_dir!" /b /ad 2^>nul ^| find /c /v ""') do set "dir_dir_count=%%d"
        
        set /a total_files+=!dir_file_count!
        set /a total_dirs+=!dir_dir_count!
        
        if !dir_file_count! gtr 0 (
            echo   - Files: !dir_file_count!
            set "has_content=1"
        )
        if !dir_dir_count! gtr 0 (
            echo   - Subdirectories: !dir_dir_count!
            set "has_content=1"
        )
        if !dir_file_count! equ 0 if !dir_dir_count! equ 0 (
            echo   - Empty directory
        )
    ) else (
        echo   - Directory does not exist (will be created)
    )
    echo.
)

echo ======================================================================
echo Total content found: !total_files! files, !total_dirs! subdirectories
echo.

rem Ask user about clearing target directories
if !has_content! equ 1 (
    echo WARNING: Target directories contain existing files and/or subdirectories.
    echo These will need to be removed before creating symbolic links.
    echo.
    :clear_confirmation
    set /p "clear_confirm=Do you want to clear all existing content from target directories? (Y/N): "
    if /i "!clear_confirm!"=="Y" goto clear_targets
    if /i "!clear_confirm!"=="N" goto skip_clear
    echo Invalid input. Please enter Y or N.
    goto clear_confirmation
) else (
    echo No existing content found in target directories.
    goto skip_clear
)

:clear_targets
echo.
echo Clearing target directories...
echo.

for /l %%i in (1, 1, !unique_target_count!) do (
    set "target_dir=!unique_target_%%i!"
    echo Clearing: !target_dir!
    
    if exist "!target_dir!\" (
        rem Remove all files in the directory
        if exist "!target_dir!\*.*" (
            del /q "!target_dir!\*.*" 2>nul
            if !errorlevel! equ 0 (
                echo   - Files cleared successfully
            ) else (
                echo   - Warning: Some files could not be deleted
            )
        )
        
        rem Remove all subdirectories
        for /d %%d in ("!target_dir!\*") do (
            rmdir /s /q "%%d" 2>nul
            if !errorlevel! equ 0 (
                echo   - Subdirectory cleared: %%~nxd
            ) else (
                echo   - Warning: Could not remove subdirectory: %%~nxd
            )
        )
    )
    echo.
)

echo Target directories cleared.
echo.

:skip_clear
echo Creating symbolic links...
echo.

for /l %%i in (1, 1, %link_count%) do (
    set "current_source=!source_%%i!"
    set "current_target=!target_%%i!"

    set "current_source=!current_source:"=!"
    set "current_target=!current_target:"=!"

    for /f "delims=" %%f in ('echo !current_source!') do set "clean_source=%%~f"
    for /f "delims=" %%n in ('echo !clean_source!') do set "source_name=%%~nxn"
    set "link_path=!current_target!\!source_name!"

    echo Processing: !clean_source!

    if not exist "!current_target!\" (
        echo   - INFO: Target directory does not exist. Creating... 
        mkdir "!current_target!"
    )

    if exist "!link_path!" (
        echo   - SKIPPED: Link or file already exists at "!link_path!"
    ) else (
        if exist "!clean_source!\" ( 
            mklink /D "!link_path!" "!clean_source!" >nul
        ) else (
            mklink "!link_path!" "!clean_source!" >nul
        )

        if !errorlevel! equ 0 (
            echo   - SUCCESS: Link created for "!source_name!"
        ) else (
            echo   - FAILED: Could not create link for "!source_name!". Error code: !errorlevel!
        )
    )
    echo.
)

echo All operations completed.

:exit_script
echo.
pause
endlocal